/* Copyright (c) 2024 Huawei Technologies Co., Ltd.
openFuyao is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN 'AS IS' BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */
import '@/styles/log.less';
import { Input, Button, Table, Space, Popover, Modal, Form, Select, message, ConfigProvider } from 'antd';
import { MoreOutlined } from '@ant-design/icons';
import { ResponseCode } from '@/common/constants';
import { getLogJobData, getLogCollectionData, addLogJob, deleteLogJob } from '@/api/containerLogApi';
import { useEffect, useState, useCallback, useRef } from 'openinula';
import { solveAnnotation, sorterFirstAlphabet } from '@/tools/utils';
import DeleteInfoModal from '@/components/DeleteInfoModal';
import zhCN from 'antd/es/locale/zh_CN';
export default function LogJob() {
  const [formType, setFormType] = useState('');
  const [jobDataSource, setJobDataSource] = useState([]);
  const [jobtableSource, setJobtableSource] = useState([]);
  const jobColumns = [
    {
      title: '任务',
      dataIndex: 'key',
      key: 'key',
      sorter: (a, b) => sorterFirstAlphabet(a.key, b.key),
    },
    {
      title: '路径',
      dataIndex: 'value',
      key: 'value',
      maxWidth: 500,
      render: (_, record) => (
        <Space size="middle" className="pathWarp">{record.value}</Space>
      ),
    },
    {
      title: '操作',
      dataIndex: '',
      key: 'x',
      render: (_, record) => (
        <Space>
          <Popover
            placement='bottom'
            content={
              <div className='pop_modal'>
                <Button type='link' onClick={() => showModal('edit', record)}>
                  修改
                </Button>
                <Button type='link' onClick={() => handleDeleteJob(record.key)}>
                  删除
                </Button>
              </div>
            }
            trigger='click'
            open={popOpen === record.key}
            onOpenChange={(newOpen) =>
              newOpen ? setPopOpen(record.key) : setPopOpen('')
            }
          >
            <MoreOutlined className='common_antd_icon primary_color' />
          </Popover>
        </Space>
      ),
    },
  ];
  const inpuRef = useRef(null);
  const [popOpen, setPopOpen] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [messageApi, contextHolder] = message.useMessage();
  const [jobDelModalOpen, setJobDelModalOpen] = useState(false);
  const [jobName, setJobName] = useState('');
  const [mainPathLength, setMainPathLength] = useState(0);
  const [isJobDelCheck, setIsJobDelCheck] = useState(false);
  const { Search } = Input;
  const successLog = (value) => {
    messageApi.open({
      type: 'success',
      content: value,
    });
  };
  const onSearchLogJob = (value) => {
    if (value) {
      setJobtableSource(jobDataSource.filter(item => item.key.includes(value)));
    } else {
      setJobtableSource(jobDataSource);
    }
  };
  const showModal = (value, data) => {
    if (value === 'edit') {
      form.setFieldValue('job', data.key);
      jobOption.map(item => {
        if (data.value.includes(item.value)) {
          form.setFieldValue('childPath', data.value.slice(item.value.length));
          form.setFieldValue('path', item.value);
        }
      });
    } else {
      form.setFieldValue('path', jobOption[0].value);
    }
    setFormType(value);
    setIsModalOpen(true);
  };
  const handleCancel = () => {
    form.resetFields();
    setIsModalOpen(false);
  };
  function handleDeleteJob(value) {
    setJobName(value);
    setJobDelModalOpen(true);
  };
  const [form] = Form.useForm();
  const [jobOption, setJobOption] = useState([{ key: '', value: '' }]);
  const handleChangeJob = (value) => {
    setMainPathLength(value.length);
    inpuRef.current.focus();
    inpuRef.current.blur();
  };
  const getLogJobList = async () => {
    const res = await getLogJobData();
    if (res.status === ResponseCode.OK) {
      setJobDataSource(solveAnnotation(res.data.data));
      setJobtableSource(solveAnnotation(res.data.data));
    };
  };
  const getJobOptions = async () => {
    const res = await getLogCollectionData();
    if (res.status === ResponseCode.OK) {
      let _arr = [];
      res.data.data[Object.keys(res.data.data)[0]].map(item => {
        _arr.push(
          { label: item.mountPath, value: item.mountPath }
        );
      });
      setJobOption(_arr);
    }
  };
  const handleOk = () => {
    let arr = { jobName: '', path: '' };
    arr.jobName = form.getFieldsValue().job;
    arr.path = form.getFieldsValue().path + form.getFieldsValue().childPath;
    addJob(arr);
  };
  const addJob = async (value) => {
    if (form.getFieldsValue().job && form.getFieldsValue().childPath) {
      try {
        const res = await addLogJob(value);
        if (res.status === ResponseCode.OK) {
          setIsModalOpen(false);
          successLog(formType === 'add' ? '添加任务成功！' : '修改任务成功！');
          form.resetFields();
          getLogJobList();
        }
      } catch (error) {
        if (error.response.status === ResponseCode.Forbidden) {
          messageApi.error('操作失败，当前用户没有操作权限，请联系管理员添加权限!');
        } else {
          messageApi.error(error.response?.data?.Msg);
        }
      }
    }
  };
  const handlePodCheckFn = (e) => {
    setIsJobDelCheck(e.target.checked);
  };
  const deleteJob = async () => {
    try {
      const res = await deleteLogJob(jobName);
      if (res.status === ResponseCode.OK) {
        successLog(`删除${jobName}任务成功！`);
        setJobDelModalOpen(false);
        setIsJobDelCheck(false);
        setJobName('');
        getLogJobList();
      }
    } catch (error) {
      if (error.response.status === ResponseCode.Forbidden) {
        messageApi.error('操作失败，当前用户没有操作权限，请联系管理员添加权限!');
      } else {
        messageApi.error(error.response?.data?.Msg);
      }
    }
  };
  const isValid = (str) => {
    return /^[0-9a-zA-Z_-]+$/.test(str);
  };
  const checkJobname = async (rule, value) => {
    if (!value) {
      throw new Error('任务名称不能为空');
    }
    if (value.length < 1 || value.length > 30) {
      throw new Error('任务名称长度应为1-30之间');
    }
    if (!isValid(value)) {
      throw new Error('任务名称应为数字、字母、_和-的组合');
    }
    return Promise.resolve();
  };
  const isPathValid = (str) => {
    return /^[A-Za-z0-9*-/_]*$/.test(str);
  };
  const checkPath = useCallback(async () => {
    let value = form.getFieldsValue().childPath;
    if (!value) {
      throw new Error('路径不能为空');
    }
    if (value.length < 6) {
      throw new Error('子路径长度最小为6');
    }
    if ((value.length + mainPathLength) > 300) {
      throw new Error('主路径和子路径长度之和应小于300');
    }
    if (!isPathValid(value)) {
      throw new Error('路径应为数字、字母、_、*、/和-的组合');
    }
    if (value[0] !== '/') {
      throw new Error('子路径应以"/"开头');
    }
    if (value.substring(value.length - 4) !== '.log') {
      throw new Error('子路径应以".log"结尾');
    }
    return Promise.resolve();
  }, [mainPathLength]);
  const handleDelJobCancel = () => {
    setJobDelModalOpen(false);
    setJobName('');
  };
  useEffect(() => {
    getLogJobList();
    getJobOptions();
  }, []);
  useEffect(() => {
    checkPath();
  }, [checkPath]);
  return (
    <div className='logJob'>
      {contextHolder}
      <div className='logJob_top'>
        <Search placeholder="请输入任务名称" onSearch={onSearchLogJob} style={{ width: 200 }} />
        <Button className='primary_btn' onClick={() => showModal('add', '')}>创建</Button>
      </div>
      <ConfigProvider locale={zhCN}>
        <Table dataSource={jobtableSource} columns={jobColumns} pagination={false} />
      </ConfigProvider>
      <Modal getContainer={false} title={formType === 'add' ? '创建采集任务' : '修改采集任务'} open={isModalOpen} onCancel={handleCancel}
        footer={[]}
      >
        <Form
          layout='vertical'
          form={form}
          name='form_in_modal'
          autoComplete="off"
          onFinish={handleOk}
          validateTrigger={['onBlur', 'onChange']}
        >
          <div className='form_model'>
            <Form.Item name='job' rules={[{ required: true, validator: checkJobname }]}
              label='任务（job_name）' style={{ marginTop: '20px' }}>
              <Input placeholder='请输入任务名称' />
            </Form.Item>
            <Form.Item name='path' label='路径（path）'>
              <Select
                onChange={handleChangeJob}
                options={jobOption}
              />
            </Form.Item>
            <Form.Item name='childPath' rules={[{ required: true, validator: checkPath }]} label='子路径'>
              <Input placeholder='请输入子路径' ref={inpuRef} />
            </Form.Item>
            <Form.Item style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '-10px' }}>
              <Button className='cancel_btn' onClick={handleCancel} style={{ marginRight: '14px' }}>取消</Button>
              <Button className='primary_btn' htmlType='submit'>确定</Button>
            </Form.Item>
          </div>
        </Form>
      </Modal>
      <DeleteInfoModal
        title="删除任务"
        open={jobDelModalOpen}
        cancelFn={handleDelJobCancel}
        content={[
          '删除任务后将无法恢复，请谨慎操作。',
          `确定删除任务 ${jobName} 吗？`,
        ]}
        isCheck={isJobDelCheck}
        showCheck={true}
        checkFn={handlePodCheckFn}
        confirmFn={deleteJob} />
    </div >
  );
}
